package com.broada.apm.servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.common.util.ZipUtil;
import com.broada.apm.es.handler.ApmDataImporter;
import com.broada.apm.indicator.api.common.ApmDataIndicatorException;
import com.broada.apm.mysql.handler.IpLocationsImporter;
import com.google.common.base.Objects;

@WebServlet("/setup")
public class InitDataServletServlet extends HttpServlet {
	/**
	 * <code>serialVersionUID</code>
	 */
	private static final long serialVersionUID = 1L;
	private static Logger log = LoggerFactory.getLogger(InitDataServletServlet.class);
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String realPath = req.getServletContext().getRealPath("/WEB-INF/database");
		String[] yamls = new File(realPath).list(new FilenameFilter() {

			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(".yaml");
			}
		});
		ObjectMapper om = new ObjectMapper();
		om.writeValue(resp.getOutputStream(), yamls);
		resp.flushBuffer();
	};

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String realPath = req.getServletContext().getRealPath("/WEB-INF/database");
		if (Objects.equal(req.getParameter("cat"), "importyaml")) {
			log.info("import data from {}", req.getParameter("file"));
			try {
				ApmDataImporter.importFromYaml(new File(realPath, req.getParameter("file")));
				resp.getWriter().println("ok");
			} catch (ApmDataIndicatorException e) {
				resp.getWriter().println(e.getLocalizedMessage());
			}
		} else if (Objects.equal(req.getParameter("cat"), "importiplocation")) {
			try {
				File map_dir = Files.createTempDirectory("apm_map").toFile();
				File ipdb_dir = Files.createTempDirectory("apm_ip_db").toFile();
				ZipUtil.unzip(new File(realPath, "map-region.zip"), map_dir, false, true);
				ZipUtil.unzip(new File(realPath, "ipdatabase.zip"), ipdb_dir, false, true);
				IpLocationsImporter ipImporter= new IpLocationsImporter();
				ipImporter.importFromFile(map_dir.listFiles()[0], ipdb_dir.listFiles()[0]);
				resp.getWriter().println("ok");
			} catch (Exception e) {
				resp.getWriter().println(e.getLocalizedMessage());
			}
		} 
		resp.flushBuffer();
	}
}
